package com.qd.panda.service.third.qd;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.cdqidi.util.DateUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 在线生成PDF
 *
 * @author sjk
 * @create 2023-05-22 15:01
 * @since 1.0.0
 */
public class PdfService {
    private PdfService(){

    }
    private static final String URL = "http://office-convert.dev.cdqidi.cn/convert_stream";

    /**
     * 在线生成pdf流
     *
     * @param response 下载
     * @param title    文件名
     * @param bytes    文件流
     */
    public static void onlinePdf(HttpServletResponse response, String title, byte[] bytes) {
        buildDownload(response, title, online(title, bytes));
    }

    /**
     * 生成PDF流
     *
     * @param title 文件名
     * @param bytes 文件流
     * @return pdf流
     */
    public static byte[] online(String title, byte[] bytes) {
        try (HttpResponse execute = HttpRequest.post(URL)
                .form("token", "7f447c2cbd601dce")
                .form("file", bytes, title+".xlsx")
                .execute()) {
            return execute.bodyBytes();
        }
    }

    public static void buildDownload(HttpServletResponse response, String title, byte[] bytes) {
        title += "(" + DateUtil.getCnStringDate() + ")";
        //解决跨域前端不能获得文件名问题
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setContentType("application/pdf");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String fileName = URLEncoder.encode(title, StandardCharsets.UTF_8).replace("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        try {
            try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
                try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
                    try (OutputStream os = response.getOutputStream()) {
                        final byte[] b = new byte[1024];
                        int len;
                        while ((len = bis.read(b)) > 0) {
                            os.write(b, 0, len);
                        }
                        os.flush();
                    }
                }
            }
        } catch (Exception ignored) {
        }
    }
}